<?php
/**
 * Advices Controller
 * 
 * @author CRIA Groep 1 <project@markvink.nl>
 * @version 1.0
 * @package controllers
 */
class AdvicesController extends AppController {
	/**
    * @var string Controller name (faster in PHP 4)
    */
	var $name = 'Advices';
	/**
    * @var string Scaffolding on prefix 
    */		
	var $scaffold = 'admin';
	
	/**
    * @var array uses following Models
    */
	var $uses = array('Advice', 'User','Laundry');
	
	/**
	 * Callback function _afterScaffoldingSave
	 * 
	 * Get triggered after savind by scaffolding
	 * @param string $method add/edit
	 * @return boolean
	 */
	function _afterScaffoldSave($method) {
		if($method == 'add') {
			$advice = $this->Advice->read();
			$users = $this->User->find('all', array(
				'conditions' => array(
					'User.id' => array_merge($this->User->findByLaundryId($advice['Advice']['laundry_id']), array(0)),
				)
			));
			foreach($users AS $user) {
				$this->__sendAdviceMail($user, $advice);
			}
		}
		return true;
	}
	
	/**
	 * Function index
	 * 
	 * Controller action
	 */
	function index(){
		$webdir = WEBROOT_DIR;
		$data = $this->Advice->find('all', array(
					'conditions' => array(
						'Laundry.id' => $this->Laundry->findByUserId($this->Auth->user('id')),
					)
				));
		$this->set(compact('data', 'webdir'));
	}
	
	/**
	 * Private function __sendAdviceMail
	 * 
	 * Sending mail to user.
	 * @param array $user send to this user
	 * @param array $advice advice about
	 */
	function __sendAdviceMail($user, $advice) {
		$this->Email->to = $user['User']['email'];
		$this->Email->subject = 'Laundrywaste.eu - Advice';
		$this->Email->template = 'advice';
		$this->set(compact('user', 'advice'));
		
		$this->Email->filePaths  = array('/home/smile/www/app/' . WEBROOT_DIR . '/' . str_replace('\\', '/', $advice['Advice']['dir']) . '/'); 
		$this->Email->attachments = array(
			$advice['Advice']['filename']
		);
		
		$this->Email->send();
	}
}
